/**
 * 步骤1测试：访问首页（cmdShowHome）
 */

import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { HttpSession } from '../src/main/request/http-session'
import { getPageParser } from '../src/main/automation/page-parser'
import { loadConfig } from '../src/main/config/index'
import { setupLogger } from '../src/main/logger/index'
import { writeFile, mkdir } from 'node:fs/promises'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const projectRoot = join(__dirname, '..')

const BASE_URL = 'https://abs1.td.gov.hk/tdab2/tdabs_external/AdminServlet_tchinese'
const SNAPSHOT_DIR = join(projectRoot, 'test-steps-snapshots')

async function saveSnapshot(name: string, html: string, metadata: any = {}) {
  await mkdir(SNAPSHOT_DIR, { recursive: true })
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  const filename = `${timestamp}_step01_${name}.html`
  const filepath = join(SNAPSHOT_DIR, filename)
  await writeFile(filepath, html, 'utf8')
  console.log(`  ✓ 快照已保存: ${filename}`)
  return filepath
}

function checkPage(html: string, stepName: string, url?: string): { success: boolean, details: Record<string, boolean> } {
  const checks = {
    hasCmdShowHome: html.includes('cmdShowHome') || url?.includes('cmdShowHome') || false,
    hasStartButton: html.includes('開始預約') || html.includes('开始预约'),
    hasForm: html.includes('form') && html.includes('frmAppointment'),
    hasTimestamp: html.includes('timestamp'),
    hasAnnouncement: html.includes('announcementMessage'),
    isHomePage: html.includes('預約運輸署') || html.includes('预约运输署'),
  }
  
  console.log(`\n📄 页面检查: ${stepName}`)
  console.log('─'.repeat(60))
  for (const [key, value] of Object.entries(checks)) {
    const icon = value ? '✓' : '✗'
    const label = key.replace(/([A-Z])/g, ' $1').trim()
    console.log(`  ${icon} ${label}`)
  }
  
  // 成功判断：有表单、时间戳，且是首页（通过按钮或页面内容判断）
  const success = checks.hasForm && checks.hasTimestamp && (checks.hasStartButton || checks.isHomePage)
  return { success, details: checks }
}

async function testStep1() {
  console.log('步骤1测试：访问首页（cmdShowHome）')
  console.log('='.repeat(60))
  
  await loadConfig()
  await setupLogger()
  
  const session = new HttpSession()
  const url = `${BASE_URL}?cmd=cmdShowHome`
  
  console.log(`\n请求: GET ${url}`)
  
  const response = await session.request({ method: 'GET', url })
  const check = checkPage(response.body, '首页响应', response.url)
  
  await saveSnapshot('home', response.body, {
    step: 1,
    url: response.url,
    status: response.status,
    check,
  })
  
  const parser = getPageParser()
  const formFields = parser.extractFormFields(response.body, 'frmAppointment')
  const fieldCount = formFields.success && formFields.data ? Object.keys(formFields.data).length : 0
  
  console.log(`\n📋 表单字段数量: ${fieldCount}`)
  
  if (!check.success) {
    console.log('\n❌ 步骤1失败：页面检查未通过')
    process.exit(1)
  }
  
  console.log('\n✓ 步骤1成功：已访问首页')
  console.log(`\n📁 快照目录: ${SNAPSHOT_DIR}`)
}

testStep1().catch((error) => {
  console.error('\n❌ 测试失败:', error)
  process.exit(1)
})

